package com.admin.system.modules.mnt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.IdUtil;
import com.admin.system.modules.mnt.dto.DatabaseQueryDTO;
import com.admin.system.modules.mnt.entity.Database;
import com.admin.system.modules.mnt.mapper.DatabaseMapper;
import com.admin.system.modules.mnt.service.DatabaseService;
import com.admin.system.modules.mnt.util.SqlUtils;
import com.admin.common.utils.PageResult;
import com.admin.common.utils.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

/**
 * @author sq-lan
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DatabaseServiceImpl extends ServiceImpl<DatabaseMapper, Database> implements DatabaseService {

    @Override
    public PageResult<Database> paging(DatabaseQueryDTO dto) {
        PageHelper.startPage(dto.getCurrent(), dto.getSize());
        List<Database> list = this.list(dto);
        return PageUtil.toPageHelper(list);
    }

    @Override
    public List<Database> list(DatabaseQueryDTO dto) {
        LambdaQueryWrapper<Database> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.hasText(dto.getName())) {
            wrapper.like(Database::getName, dto.getName());
        }
        if (StringUtils.hasText(dto.getJdbcUrl())) {
            wrapper.eq(Database::getJdbcUrl, dto.getJdbcUrl());
        }
        if (dto.getCreateTime() != null && !dto.getCreateTime().isEmpty()) {
            wrapper.between(Database::getCreateTime, dto.getCreateTime().get(0), dto.getCreateTime().get(1));
        }
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Database entity) {
        entity.setId(IdUtil.simpleUUID());
        save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modify(Database entity) {
        Database database = getById(entity.getId());
        BeanUtil.copyProperties(entity, database, CopyOptions.create().setIgnoreNullValue(true));
        saveOrUpdate(database);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(Set<String> ids) {
        removeByIds(ids);
    }

    @Override
    public boolean testConnection(Database entity) {
        try {
            return SqlUtils.testConnection(entity.getJdbcUrl(), entity.getUserName(), entity.getPwd());
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

}
